// 获取应用实例
const app = getApp();

Page({
  data: {
    stats: {
      totalCount: 0,
      masteredCount: 0,
      reviewCount: 0
    },
    currentCategory: 'all',
    categories: [],
    questionList: []
  },

  onLoad() {
    this.loadPageData();
  },

  onPullDownRefresh() {
    this.loadPageData().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 加载页面数据
  loadPageData() {
    return Promise.all([
      this.loadStats(),
      this.loadCategories(),
      this.loadQuestionList()
    ]);
  },

  // 加载统计信息
  loadStats() {
    return app.request({
      url: '/wrong-questions/stats',
      method: 'GET'
    }).then(res => {
      if (res.code === 0) {
        this.setData({
          stats: res.data
        });
      }
    }).catch(() => {
      app.showError('获取统计信息失败');
    });
  },

  // 加载分类列表
  loadCategories() {
    return app.request({
      url: '/wrong-questions/categories',
      method: 'GET'
    }).then(res => {
      if (res.code === 0) {
        this.setData({
          categories: res.data.list
        });
      }
    }).catch(() => {
      app.showError('获取分类列表失败');
    });
  },

  // 加载错题列表
  loadQuestionList() {
    app.showLoading();
    return app.request({
      url: '/wrong-questions/list',
      method: 'GET',
      data: {
        categoryId: this.data.currentCategory === 'all' ? '' : this.data.currentCategory
      }
    }).then(res => {
      app.hideLoading();
      if (res.code === 0) {
        this.setData({
          questionList: res.data.list
        });
      }
    }).catch(() => {
      app.hideLoading();
      app.showError('获取错题列表失败');
    });
  },

  // 选择分类
  selectCategory(e) {
    const category = e.currentTarget.dataset.category;
    if (category === this.data.currentCategory) return;
    
    this.setData({
      currentCategory: category
    }, () => {
      this.loadQuestionList();
    });
  },

  // 跳转到题目详情
  goToQuestion(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/exam-question/exam-question?id=${id}`
    });
  },

  // 复习题目
  reviewQuestion(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/exam-question/exam-question?id=${id}&mode=review`
    });
  },

  // 移除错题
  removeQuestion(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认移除',
      content: '确定要将此题从错题本中移除吗？',
      success: (res) => {
        if (res.confirm) {
          app.request({
            url: `/wrong-questions/remove/${id}`,
            method: 'POST'
          }).then(res => {
            if (res.code === 0) {
              app.showSuccess('移除成功');
              this.loadPageData();
            }
          }).catch(() => {
            app.showError('移除失败');
          });
        }
      }
    });
  }
}); 